var fs = require('fs')
var util = require('../utility/util.js')
var dirPath = require('../config/pathConfig.js').activePath

var safePathCheck = util.safePathCheck
var fileName = 'actives.data'

var aPageCount = 5 // 特殊
module.exports = {

  find: function(filter, callback) {
    safePathCheck(dirPath, fileName, function(exists) {
      if (exists) {
        var data = fs.readFileSync(dirPath + fileName)
        if (!data.length) {
          data = []
        } else {
          data = JSON.parse(data)
        }
        data.reverse()

        if (filter.userId) {
          var id = filter.userId
          data = data.filter(function(active) {
            switch (+active.type) {
              case 4:
                return true;
              case 1:
                return active.active.handler.id == id
              case 2:
                return active.active.targeter.id == id || active.active.handler.id == id
            }
          })
        }

        if (filter.page) {
          var page = filter.page
          data = data.slice((page - 1) * aPageCount, page * aPageCount)
        }

        callback(null, data)
      } else {
        callback(null, [])
      }
    })
  },
  insert: function(content) {
    safePathCheck(dirPath, fileName, function(exists) {
      if (!exists) {
        var data = []
      } else {
        var data = fs.readFileSync(dirPath + fileName)
        data = JSON.parse(data)
      }
      data.push(content)
      data = JSON.stringify(data, null, 4)
      fs.writeFileSync(dirPath + fileName, data)
    })
  }
}